import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		// 用户信息
		userInfo: JSON.parse(uni.getStorageSync('userInfo') || '{}'),
		//登录标志
		hasLogin: uni.getStorageSync('userInfo') ? true : false,
		
		// 已存在用户的id
		user_id:'',
		
		// 存放编辑器的数据
		editContent:[]
	},
	mutations: {
		getUserInfo(state,userInfo){
			uni.setStorageSync('userInfo',JSON.stringify(userInfo))
			state.userInfo = userInfo;
			state.hasLogin = true;
		}, // 获取授权信息
		
		setUserId(state,id){
			state.user_id = id;
		}, //设置用户id
		
		addEditContent(state,content){
			for(let i=0;i<state.editContent.length;i++){
				if(state.editContent[i].id === content.id){
					if(state.editContent[i].type === 'txt'){
						state.editContent[i].content = content.content;
					}else{
						state.editContent[i].des = content.des;
						state.editContent[i].src = content.src;
					}
					console.log(state.editContent);
					return;
				}
			}
			
			state.editContent.push(content);
			console.log('store-editContent:',state.editContent);
		}, //添加编辑器内容
		
		delEditContent(state,content){
			for(let i=0;i<state.editContent.length;i++){
				if(state.editContent[i].id === content.id){
					state.editContent.splice(i,1);
					console.log(state.editContent);
					return;
				}
			}
		},
		clearEditContent(state){
			state.editContent = [];
		} //清空编辑器内容
	},
    getters:{
		
    },
	actions: {
		registeUser:function({state,commit}){
			console.log(state.user_id);
			if(state.user_id !== ''){
				return;
			}else if(!state.hasLogin){
				return;
			}else{
				return new Promise((resolve,reject)=>{
					uniCloud.callFunction({
						name: 'user',
						data: {
							userInfo:state.userInfo,
							type:'addUser'
						}
					})
					.then((res)=>{
						console.log('添加用户成功：',res)
						commit('setUserId',res.result.id)
						resolve(res.result.id);
					})
					.catch((err) => {
						reject(err)
					})
				})
			}
		},
		getUserId:function({state,commit}){
			if(!state.hasLogin || state.user_id !== ''){
				return
			}else{
				return new Promise((resolve,reject) => {
					uniCloud.callFunction({
						name:'user',
						data:{
							type:'getUser',
							userInfo:state.userInfo
						}
					})
					.then((res)=>{
						console.log('查询用户的结果：',res);
						if(res.result.data.length !== 0){
							commit('setUserId',res.result.data[0]._id);
						}
						resolve(res.result.data)
					}).catch((err) => {
						reject(err)
					})
				})
			}
			
		}
	}
})

export default store
